import com.bbibm.property.api.entity.SafetyCallon;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.bouncycastle.util.encoders.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Path;

/**
 * 获取二维码
 */
public class QRCodeWriterUtils {

	/**
	 * 获取二维码图片链接
	 *		<!--二维码模块-->
	 * 		<dependency>
	 * 			<groupId>com.google.zxing</groupId>
	 * 			<artifactId>core</artifactId>
	 * 			<version>3.3.0</version>
	 * 		</dependency>
	 * 		<dependency>
	 * 			<groupId>com.google.zxing</groupId>
	 * 			<artifactId>javase</artifactId>
	 * 			<version>3.3.0</version>
	 * 		</dependency>
	 * @param callonId
	 */
	public static String getQRCodeImageUrl(String callonId) throws IOException {
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		BitMatrix bitMatrix = null;
		String fileContentBase64 = null;
		InputStream in = null;
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			bitMatrix = qrCodeWriter.encode(callonId, BarcodeFormat.QR_CODE, 250, 250);
			MatrixToImageConfig DEFAULT_CONFIG = new MatrixToImageConfig();
			BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix, DEFAULT_CONFIG);
			ImageIO.write(bufferedImage, "jpg", os);
			in = new ByteArrayInputStream(os.toByteArray());
			byte[] data = new byte[in.available()];
			in.read(data);
			in.close();
			//对字节数组Base64编码
			if (data == null || data.length == 0) {
				return null;
			}
			fileContentBase64 = "data:jpg;base64,"+Base64.toBase64String(data);
			if (fileContentBase64 == null || "".equals(fileContentBase64)) {
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriterException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
			}
		}
		return fileContentBase64;
	}
}
